package com.manage.common.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Set;


/**
 * @Create by ldr.
 * @create 2018-09-08 9:55
 * @Description：登陆拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private final static Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String basePath = request.getContextPath();
        String path = request.getRequestURI();
		log.info("------>preHandle<------path:"+path);

        if(!doLoginInterceptor(path, basePath) ){//是否进行登陆拦截
            return true;
        }

        //获取session
        HttpSession session = request.getSession(true);
        //判断用户ID是否存在，不存在就跳转到登录界面
        if (session.getAttribute("user") == null){
            log.info("没有登陆");
            response.sendRedirect(request.getContextPath()+"/user/login");
            return false;
        }else {
            session.setAttribute("user",session.getAttribute("user"));
            return true;
        }

    }

    /**
     * 是否进行登陆过滤
     * @param path
     * @param basePath
     * @return
     */
    private boolean doLoginInterceptor(String path,String basePath){
        path = path.substring(basePath.length());
        Set<String> notLoginPaths = new HashSet<>();
        //设置不进行登录拦截的路径：登录注册和验证码
        //notLoginPaths.add("/");
        notLoginPaths.add("/user/update");//修改密码
        notLoginPaths.add("/user/subLogin");//登录
        if(notLoginPaths.contains(path)) return false;
        return true;
    }

}
